package cn.zust.itcost.controller;

import cn.zust.itcost.common.R;
import cn.zust.itcost.entity.User;
import cn.zust.itcost.service.UserService;
import cn.zust.itcost.utils.SMSUtils;
import cn.zust.itcost.utils.ValidateCodeUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Map;

/*求职用户管理*/

@Slf4j
@CrossOrigin
@Transactional
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     *
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/login")
    public R<Object> login(HttpServletRequest request, @RequestBody User user){
        System.out.println(user.toString());
        //对前端密码加密
        String password = user.getPassword();
//        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //根据用户名查数据库
        LambdaQueryWrapper<User> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getName,user.getName());//等值查询
        User user1 = userService.getOne(queryWrapper);


        //数据是否存在
        if (user1 == null){
            return R.fail().message("登录失败,用户不存在");
        }

        //密码比对
        if (!user1.getPassword().equals(password)){
            return R.fail().message("密码错误");
        }

        //登录成功，id放入Session，返回结果
        request.getSession().setAttribute("employee",user1.getId());
        return R.ok(user1);
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清除session中id
        request.getSession().removeAttribute(("user"));
        return R.ok("退出成功");
    }


    /**
     * 注册
     *
     * @param user
     * @return
     */
    @PostMapping("/enroll")
    public R<Object> enroll(@RequestBody User user){
        log.info("新增信息：{}",user.toString());

        //密码md5加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));

        //根据用户名查数据库
        LambdaQueryWrapper<User> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getName,user.getName());//等值查询
        User user1 = userService.getOne(queryWrapper);

        if (user1!=null){
            return R.fail().message("用户名已存在");
        }

        //初始值
        user.setWxcount("暂无");
        user.setGraduation("暂无");
        user.setBirthday("暂无");
        user.setEmail("暂无");


        //当前时间
        user.setSettime(LocalDateTime.now());

        userService.save(user);

        return R.ok().message("新增成功");
    }

    /**
     * 发送手机短信验证码
     *
     * @param id
     * @param session
     * @return
     */
    @PostMapping("/sendMsg/{id}")
    public R<Object> sendMSg(@PathVariable Long id, HttpSession session){

        User user = userService.getById(id);

        //获取手机号
        String phone = user.getPhone();

        if (phone==null){
            return R.ok().message("未绑定手机号");
        }

        if (StringUtils.isNotEmpty(phone)){
            //生成随机验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);

            //保存验证码到Sess
            session.setAttribute(phone,code);

            return R.ok().message("短信发送成功"+code);
        }
        return R.fail().message("短信发送失败");
    }

    /**
     * 发送手机短信验证码2
     *
     * @param session
     * @return
     */
    @PostMapping("/sendMsg2")
    public R<Object> sendMSg2(@RequestBody User user, HttpSession session){

        //获取手机号
        String phone = user.getPhone();

        if (phone==null){
            return R.ok().message("未绑定手机号");
        }

        if (StringUtils.isNotEmpty(phone)){
            //生成随机验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);

            //调用aliyun(签名//注册失败)
            SMSUtils.sendMessage("平台名","SMS_295705213",phone,code);

            //保存验证码到Sess
            session.setAttribute(phone,code);

            return R.ok().message("短信发送成功"+code);
        }
        return R.fail().message("短信发送失败");
    }

    /**
     * 验证码登录
     *
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/Msglogin")
    public R<Object> login(@RequestBody Map map, HttpSession session){
        log.info(map.toString());

        //获取手机号
        String phone = map.get("phone").toString();

        //获取验证码
        String code = map.get("code").toString();

        //从session获取保存的验证码
        Object codeInSession = session.getAttribute(phone);

        //进行比对
        if (codeInSession != null && codeInSession.equals(code)){

            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);

            User user = userService.getOne(queryWrapper);
            if (user == null){
                return R.fail().message("用户不存在");
            }

            return R.ok(user);

        }
        return R.fail().message("登录失败");
    }


    /**
     * 查询个人信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Object> getById(@PathVariable Long id){
        log.info(("根据id查询信息"));
        User user = userService.getById(id);
        if (user != null){
            return R.ok(user);
        }
        return R.fail().message("没有查询到对应用户信息");
    }


    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @PutMapping("/updata")
    public R<User> updata(@RequestBody User user){
        log.info(user.toString());

        long id = Thread.currentThread().getId();
        log.info("线程id为：{}",id);

        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));

        userService.updateById(user);

        return R.ok(user);
    }

}
